import { useState } from "react";
import { useTasks, useTasksDispatch } from "../context/TasksContext.js";
import { actionChanged, actionDeleted } from "../reducer/tasksReducer.js";

export default function TaskList() {
  const tasks = useTasks();
  return (
    <ul>
      {tasks.map((task) => (
        <li key={task.id}>
          <Task task={task} />
        </li>
      ))}
    </ul>
  );
}

function Task({ task }) {
  const [isEditing, setIsEditing] = useState(false);
  const dispatch = useTasksDispatch();
  let taskContent;
  if (isEditing) {
    taskContent = (
      <>
        <input
          value={task.text}
          onChange={(e) => {
            dispatch(
              actionChanged({
                ...task,
                text: e.target.value,
              })
            );
          }}
        />
        <button onClick={() => setIsEditing(false)}>Save</button>
      </>
    );
  } else {
    taskContent = (
      <>
        {task.text}
        <button onClick={() => setIsEditing(true)}>Edit</button>
      </>
    );
  }

  return (
    <label>
      <input
        type="checkbox"
        checked={task.done}
        onChange={(e) => {
          dispatch(
            actionChanged({
              ...task,
              done: e.target.checked,
            })
          );
        }}
      />
      {taskContent}
      <button
        onClick={() => {
          dispatch(actionDeleted(task.id));
        }}
      >
        Delete
      </button>
    </label>
  );
}
